//
//  ZYPopTimerRequest.m
//  DesignMode
//
//  Created by wangzhipan on 2024/11/25.
//

#import "ZYPopTimerRequest.h"

@interface ZYPopTimerRequest()
@property (nonatomic, assign) CGFloat duration;
@property (nonatomic, strong, nullable) NSTimer *timer;


@property (nonatomic, assign) NSInteger count;
@end

@implementation ZYPopTimerRequest

- (void)doShow
{
    [super doShow];
    [self p_startTimerOfDuration:self.duration];
}

- (void)doInterrupt
{
    [super doInterrupt];
    [self p_pause];
}

- (void)doResume
{
    [super doResume];
    [self p_resume];
}


- (void)doClose:(BOOL)inQueue
{
    [self p_cancle];
    [super doClose:inQueue];
}

- (void)p_startTimerOfDuration:(CGFloat)duration
{
    self.duration = duration;
    if (self.timer) {
        [self.timer invalidate];
    }
    __weak typeof(self) weakSelf = self;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1 repeats:YES block:^(NSTimer * _Nonnull timer) {
        [weakSelf p_updateTimer];
    }];
    [[NSRunLoop mainRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}

- (void)p_pause
{
    [self.timer invalidate];
    self.timer = nil;
}

- (void)p_resume
{
    [self p_startTimerOfDuration:self.duration - self.count];
}

- (void)p_cancle
{
    self.count = 0;
    [self.timer invalidate];
    self.timer = nil;
}


- (void)p_updateTimer
{
    self.count++;
    if (self.count >= self.duration) {
        [self doClose:NO];
    }
}


- (void)dealloc
{
    [self.timer invalidate];
    self.timer = nil;
}
@end
